<?php

namespace App\Http\Controllers;

use App\Models\Link;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class IndexController
{
    public function index()
    {
        return view('index', [
            'currUrl' => env('REDIRECT_HOST')
        ]);
    }

    public function handle(Request $req)
    {
        $url = $req->get('url');
        if (!$url) {
            return response()->json([
                'code' => 500,
                'msg' => '缺少url',
                'data' => []
            ]);
        }
        $ip = $req->ip();
        if ($existUrl = Link::where('origin', $url)->first()) {
            return response()->json([
                'code' => 201,
                'msg' => '已存在',
                'data' => [
                    'code' => $existUrl->code
                ]
            ]);
        }
        if (
            !empty($ifIpRecently = Link::where('create_ip', $ip)->orderByDesc('create_time')->first()) &&
            time() - strtotime($ifIpRecently->toArray()['create_time']) < 60
        ) {
            return response()->json([
                'code' => 500,
                'msg' => '请一分钟后再试',
                'data' => []
            ]);
        }

        do {
            $newCode = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'), 0, 6);
        } while(!empty(Link::where('code', $newCode)->get()->toArray()));

        $link = new Link;
        $link->code = $newCode;
        $link->origin = $url;
        $link->create_ip = $req->ip();
        $link->create_time = date('Y-m-d H:i:s');
        $link->save();

        return response()->json([
            'code' => 200,
            'msg' => '成功',
            'data' => [
                'code' => $newCode
            ]
        ]);
    }

    public function visit($code) {
        $link = Link::where('code', $code)->first();
        if (preg_match("/^(http:\/\/|https:\/\/)(([A-Za-z0-9-_~]+)\.)+([A-Za-z0-9-_~\/])+$/", $link['origin'])) {
            return redirect()->away($link['origin']);
        }
        return view('redirect', [
            'link' => $link
        ]);
    }
}
